package com.cn.lotary.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * for backup database
 *
 * @author Jason 14-Jul-2011
 */
public class DatabaseUitl {

    public DatabaseUitl() {
    }

    /**
     *
     * @param host server name
     * @param user user
     * @param password password
     * @param databaseName database name
     * @param savePath backup file save path
     */
    public static String backupDatabase(String host, String user, String password, String databaseName, String savePath) {
        File file = new File(savePath);

        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (SecurityException e) {
                return "no permission on this path: " + savePath;
            }
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        String command = "mysqldump -h " + host + " -u " + user + " -p" + password + " " + databaseName + " |gzip > " + savePath + databaseName + dateFormat.format(new Date()) + ".sql.gz";
        try {
            Runtime.getRuntime().exec(new String[]{"bash", "-c", command});
            return MessageBundle.SUCCESS;
        } catch (IOException ex) {
            LoggerUtils.error(ex);
            Mailer.sendMail(null, null, "DataBase Backup Faild", ex.getMessage());
            return MessageBundle.FAILURE;
        }
    }
}
